<template>
  <div :id="TableColumnData.tableId" class="table-item" :data-obj="JSON.stringify(TableColumnData)">
    <je-panel>
      <template #top>
        <div class="title">
          <i :class="TableColumnData.iconCls"></i>
          <span>{{ TableColumnData.tableName }}（{{ TableColumnData.tableCode }}）</span>
          <i class="widthIcon jeicon jeicon-width" @click="updateHeight"></i>
          <i class="delIcon fal fa-times" @click="delTable"></i>
        </div>

        <je-input-search
          v-model:value="searchValue"
          class="inputsearch"
          style="height: 32px"
          allow-clear
          :placeholder="$t('searchText')"
          @search="queryTable('input')"
          ><template #prefix><i class="fal fa-search" /> </template>
        </je-input-search>
      </template>
      <template #default>
        <je-table
          ref="xTable"
          border
          auto-resize
          :stripe="false"
          show-overflow="ellipsis"
          :data="tableColumn"
          resizable
          :loading="loading"
          size="mini"
          class="view-designtable"
          height="100%"
          :scroll-y="{ mode: 'wheel' }"
          header-align="center"
          @checkbox-change="checkboxChange"
          @checkbox-all="checkboxChangeAll"
        >
          <je-column type="checkbox" width="40"></je-column>
          <je-column field="TABLECOLUMN_CODE" :title="$t('viewModal.designView.columnName')">
            <template #default="{ row }">
              <span
                :class="[row.TABLECOLUMN_CLASSIFY == 'SYS' ? 'changeColor' : '']"
                v-html="formatSearchData(row.TABLECOLUMN_NAME + '（' + row.TABLECOLUMN_CODE + '）')"
              >
              </span>
            </template>
          </je-column>
        </je-table>
      </template>
      <template #bottom>
        <div class="footer">
          <span :class="[queryType == 'PRO,SYS' ? 'select' : '']" @click="queryTable('PRO,SYS')">
            {{ $t('viewModal.designView.btnAll') }}
          </span>
          <span
            class="footer-center"
            :class="[queryType == 'PRO' ? 'select' : '']"
            @click="queryTable('PRO')"
          >
            {{ $t('viewModal.designView.btnProField') }}
          </span>
          <span
            style="border-right: 1px solid #e6e6e6"
            :class="[queryType == 'SYS' ? 'select' : '']"
            @click="queryTable('SYS')"
          >
            {{ $t('viewModal.designView.btnSysField') }}
          </span>
          <span
            :class="[queryType == 'noChecked' ? 'select' : '']"
            @click="queryTable('noChecked')"
          >
            {{ $t('viewModal.designView.btnNoChecked') }}
          </span>
        </div>
      </template>
    </je-panel>
  </div>
</template>

<script>
  import { defineComponent, ref, watch, nextTick, onMounted } from 'vue';
  import { Input, Grid, Modal, Panel } from '@jecloud/ui';
  import { isNotEmpty } from '@jecloud/utils';
  import { getColumnData } from '../../api/index';

  export default defineComponent({
    name: 'DesignTable',
    components: {
      JeInputSearch: Input.Search,
      JeTable: Grid,
      JeColumn: Grid.Column,
      JePanel: Panel,
    },
    props: {
      tabelDatas: {
        type: Object,
        required: true,
      },
      plumbIns: {
        type: Object,
        default: () => {
          return {};
        },
      },
      selectCode: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    emits: ['monitorDelete', 'checkChange'],
    setup(props, { emit }) {
      const TableColumnData = ref(props.tabelDatas);
      const plumbJs = ref(props.plumbIns);
      const xTable = ref(null);
      const selectFieldCode = ref(props.tabelDatas.selectCode);
      const tableColumn = ref([]);
      const queryType = ref('PRO,SYS');
      const searchValue = ref('');
      const queryLogo = ref(false);

      const loading = ref(true);

      onMounted(() => {
        queryTable('PRO,SYS');
      });

      watch(
        () => searchValue.value,
        (newVal) => {
          if (!newVal) {
            searchType.value = false;
          }
        },
      );

      //过滤表数据
      const queryTable = (type) => {
        loading.value = true;
        searchType.value = false;
        if (type != 'input') {
          queryType.value = type;
        }
        // 数据搜索标识
        if (
          ['PRO', 'SYS', 'noChecked'].indexOf(type) != -1 ||
          (type == 'input' && isNotEmpty(searchValue.value))
        ) {
          queryLogo.value = true;
        } else {
          queryLogo.value = false;
        }
        //
        const custom = [
          {
            type: '=',
            code: 'TABLECOLUMN_RESOURCETABLE_ID',
            value: TableColumnData.value.tableId,
          },
          {
            type: '=',
            code: 'TABLECOLUMN_ISCREATE',
            value: '1',
            cn: 'and',
          },
          {
            type: 'and',
            value: [
              {
                type: 'like',
                code: 'TABLECOLUMN_CODE',
                value: searchValue.value.trim(),
                cn: 'or',
              },
              {
                type: 'like',
                code: 'TABLECOLUMN_NAME',
                value: searchValue.value.trim(),
                cn: 'or',
              },
            ],
          },
        ];
        if (queryType.value == 'noChecked') {
          custom.push({ type: 'notIn', code: 'TABLECOLUMN_CODE', value: selectFieldCode.value });
        } else {
          custom.push({ type: 'in', code: 'TABLECOLUMN_CLASSIFY', value: queryType.value });
        }
        const j_query = {
          custom,
          order: [{ code: 'TABLECOLUMN_CLASSIFY' }, { code: 'SY_ORDERINDEX' }],
        };
        const params = {
          tableCode: 'JE_CORE_TABLECOLUMN',
          j_query: JSON.stringify(j_query),
          limit: -1,
        };
        getColumnData(params)
          .then((obj) => {
            if (type && searchValue.value) {
              searchType.value = true;
            }
            getXTable()
              .reloadData(obj.rows)
              .then(() => {
                setSelectInfo();
              });
            loading.value = false;
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      const delTable = () => {
        const Id = TableColumnData.value.tableId;
        // 获取JsPlumb对象内所有线数据
        const connections = plumbJs.value.getAllConnections();
        for (var i in connections) {
          if (connections[i].sourceId === Id || connections[i].targetId === Id) {
            // 删除相匹配的线
            plumbJs.value.deleteConnection(connections[i]); // deleteConnection(@) 删除链接线  @线对象
          }
        }
        emit('monitorDelete', Id);
        //级联删除输出视图的数据;
        emit('checkChange', {
          type: 'deleteTable',
          tableCode: TableColumnData.value.tableCode,
        });
      };

      //根据数据选中列
      const setSelectInfo = () => {
        if (selectFieldCode.value != undefined && selectFieldCode.value.length > 0) {
          const tableData = getXTable().getTableData().fullData;
          selectFieldCode.value.forEach((item) => {
            tableData.forEach((record) => {
              if (record.TABLECOLUMN_CODE == item) {
                getXTable().setCheckboxRow(record, true);
              }
            });
          });
        } else {
          selectFieldCode.value = [];
        }
      };

      //列表checkbox改变事件
      const checkboxChange = ({ checked, row }) => {
        //选中
        if (checked) {
          let flag = true;
          selectFieldCode.value.forEach((code) => {
            if (code == row.TABLECOLUMN_CODE) {
              flag = false;
            }
          });
          if (flag) {
            selectFieldCode.value.push(row.TABLECOLUMN_CODE);
            //改变关系设置列表的数据
            const recored = [
              {
                value: TableColumnData.value.tableCode + '.' + row.TABLECOLUMN_CODE,
                tableCode: TableColumnData.value.tableCode,
                tableName: TableColumnData.value.tableName,
                column: row.TABLECOLUMN_CODE,
                name: row.TABLECOLUMN_NAME,
                dataType: row.TABLECOLUMN_TYPE,
                length: row.TABLECOLUMN_LENGTH,
                grouping: false,
                sort: '',
                formula: '',
                whereColum: '',
              },
            ];
            emit(
              'checkChange',
              {
                type: 'add',
              },
              recored,
            );
          }
          //取消选中
        } else {
          selectFieldCode.value.forEach((code, index) => {
            if (code == row.TABLECOLUMN_CODE) {
              selectFieldCode.value.splice(index, 1);
              emit(
                'checkChange',
                {
                  type: 'delete',
                },
                [TableColumnData.value.tableCode + '.' + row.TABLECOLUMN_CODE],
              );
            }
          });
        }
      };
      // 全选
      const checkboxChangeAll = ({ checked, records }) => {
        // 选中
        if (checked) {
          // 如果没有过滤数据
          if (!queryLogo.value) {
            selectFieldCode.value = [];
            records.forEach((item) => {
              selectFieldCode.value.push(item.TABLECOLUMN_CODE);
            });
            emit(
              'checkChange',
              {
                type: 'addAll',
                tableCode: TableColumnData.value.tableCode,
                tableName: TableColumnData.value.tableName,
              },
              records,
            );
          } else {
            const addRecords = [];
            records.forEach((item) => {
              if (selectFieldCode.value.indexOf(item.TABLECOLUMN_CODE) == -1) {
                selectFieldCode.value.push(item.TABLECOLUMN_CODE);
                addRecords.push({
                  value: TableColumnData.value.tableCode + '.' + item.TABLECOLUMN_CODE,
                  tableCode: TableColumnData.value.tableCode,
                  tableName: TableColumnData.value.tableName,
                  column: item.TABLECOLUMN_CODE,
                  name: item.TABLECOLUMN_NAME,
                  dataType: item.TABLECOLUMN_TYPE,
                  length: item.TABLECOLUMN_LENGTH,
                  grouping: false,
                  sort: '',
                  formula: '',
                  whereColum: '',
                });
              }
            });
            emit(
              'checkChange',
              {
                type: 'add',
              },
              addRecords,
            );
          }
        } else {
          // 如果没有过滤数据
          if (!queryLogo.value) {
            selectFieldCode.value = [];
            emit('checkChange', {
              type: 'deleteTable',
              tableCode: TableColumnData.value.tableCode,
            });
          } else {
            const deleteField = [];
            const tableData = getXTable().getTableData().fullData;
            const tableDataFields = [];
            tableData.forEach((item) => {
              tableDataFields.push(item.TABLECOLUMN_CODE);
            });
            // 删除数据
            for (let index = 0; index < selectFieldCode.value.length; index++) {
              const item = selectFieldCode.value[index];
              if (tableDataFields.indexOf(item) != -1) {
                deleteField.push(TableColumnData.value.tableCode + '.' + item);
                selectFieldCode.value.splice(index, 1);
                index--;
              }
            }
            emit(
              'checkChange',
              {
                type: 'delete',
              },
              deleteField,
            );
          }
        }
      };

      //获得列表对象
      const getXTable = () => {
        return xTable.value.$plugin;
      };

      const searchType = ref(false);
      const formatSearchData = (name) => {
        let text = name;
        if (name && name != undefined && searchValue.value.length > 0 && searchType.value) {
          var re = new RegExp(searchValue.value, 'g');
          let replaceString = '<span style="color:red;">' + searchValue.value + '</span>';
          text = name.replace(re, replaceString);
        }
        return text;
      };

      //改变高度
      const updateHeight = (obj) => {
        const doc = document.getElementById(TableColumnData.value.tableId);
        if (doc) {
          if (doc.clientHeight == '498') {
            const zHeight = doc.parentNode.parentNode.clientHeight;
            doc.style.height = zHeight + 'px';
            doc.style.top = '0';
          } else {
            if (props.tabelDatas.top && props.tabelDatas != '') {
              doc.style.top = props.tabelDatas.top;
            }
            doc.style.height = '500px';
          }
        }
      };

      return {
        queryTable,
        TableColumnData,
        delTable,
        xTable,
        selectFieldCode,
        getXTable,
        setSelectInfo,
        checkboxChange,
        checkboxChangeAll,
        tableColumn,
        queryType,
        searchValue,
        allowclear: true,
        formatSearchData,
        searchType,
        updateHeight,
        loading,
      };
    },
  });
</script>

<style lang="less" scoped>
  .table-item {
    .title {
      height: 30px;
      line-height: 30px;
      font-size: 14px;
      position: relative;
      color: #333333;
      padding: 0 10px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      background: #f7f9fc;
      border-left: 1px solid #e6e6e6;
      border-right: 1px solid #e6e6e6;
      span {
        margin-left: 10px;
      }
      .delIcon {
        position: absolute;
        right: 10px;
        top: 6px;
        font-size: 16px;
        cursor: pointer;
      }
      .widthIcon {
        top: -1px;
        position: absolute;
        right: 30px;
        font-size: 16px;
        cursor: pointer;
      }
    }
    .inputsearch {
      border-color: #e6e6e6 !important;
      border-radius: 0;
    }
    .ant-input-affix-wrapper:hover {
      border: 1px solid #5c8dff !important;
      box-shadow: none !important;
    }
    .ant-input-affix-wrapper-focused {
      border: 1px solid #5c8dff !important;
      box-shadow: none !important;
    }
    .footer {
      height: 32px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      text-align: center;
      line-height: 32px;
      color: #555555;
      font-size: 14px;
      background: #ffffff;
      border-top: 1px solid #e6e6e6;
      border-left: 1px solid #e6e6e6;
      span {
        cursor: pointer;
        display: inline-block;
        text-align: center;
        width: 25%;
      }
      .select {
        color: #3265f5;
      }
      .footer-center {
        border-left: 1px solid #e6e6e6;
        border-right: 1px solid #e6e6e6;
      }
    }
    .view-designtable {
      .changeColor {
        color: #3265f5 !important;
      }
    }
  }
</style>
<style lang="less">
  .table-item {
    .ant-input-group-addon {
      display: none;
    }
    .view-designtable {
      border-left: 1px solid #e6e6e6;
    }
    .ant-input-affix-wrapper:hover {
      border: 1px solid #5c8dff !important;
      box-shadow: none !important;
    }
    .ant-input-affix-wrapper {
      border-color: #e6e6e6 !important;
      border-radius: 0;
    }
    .ant-input-affix-wrapper-focused {
      border: 1px solid #5c8dff !important;
      box-shadow: none !important;
    }
    .ant-input-affix-wrapper {
      border-radius: 0 !important;
    }
  }
</style>
